home *** CD-ROM | disk | FTP | other *** search
- Path: news.iag.net!news
- From: jatmon@iag.net (John R Buchan)
- Newsgroups: comp.lang.c
- Subject: Re: gets() question
- Date: 7 Jan 1996 18:17:28 GMT
- Organization: Internet Access Group, Orlando, Florida
- Message-ID: <4cp2no$h9l@news.iag.net>
- References: <4cosgf$rir@newsbf02.news.aol.com>
- NNTP-Posting-Host: pm3-orl11.iag.net
- X-Newsreader: WinVN 0.99.7
-
- In article <4cosgf$rir@newsbf02.news.aol.com>, simpsondg@aol.com says...
- <snip>
- >#include "stdio.h"
- >
- >void main(void)
- >{
- > int i[5];
- > char s[3][10];
- >
- > printf ("Enter s[0]: ");
- > gets (s[0]);
- >
- > printf ("Enter i[0]]: ");
- > scanf ("%d",&i[0]);
- >
- > printf ("Enter s[1]: ");
- > gets (s[1]); /* this gets() doesn't wait for input */
- >
- > printf ("Enter i[1]]: ");
- > scanf ("%d",&i[1]);
- >}
-
- This is one of the side effects of scanf that is explained in the c.l.c faq
- (Frequently Asked Question) list. The list is available for anonymous ftp
- from rtfm.mit.edu /pub/usenet/comp.lang.c.
-
- Basically, when scanf is used to input numbers (and few other circumstances)
- it stops reading when it reaches the first char that doesn't fit its
- conversion type. Since '\n' isn't in the list of acceptable chars for an
- int ("%d"), scanf stops reading and leaves it on the stream. When the next
- gets is executed, it will stop reading with the first '\n', which is the one
- left behind by the scanf. So, it isn't actually skipped over, it just reads
- a blank line.
-
- As a general rule it is safer and easier to use fgets for any user input,
- instead of gets or scanf. If you are reading a string, remember that fgets
- leaves the '\n' attached. For any other input fgets it to a buffer and
- use sscanf, strtok, etc to parse the buffer.
-
- --
- John R Buchan -:|:- Looking for that elusive FAQ? ftp to:
- jatmon@mail.iag.net -:|:- rtfm.mit.edu /pub/usenet-by-group/....
-
-